package com.hankol.material.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseFragment
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.EventBusUtils
import com.google.android.material.appbar.AppBarLayout
import com.hankol.material.R
import com.hankol.material.adapter.ContentListFolderAdapter
import com.hankol.material.adapter.ContentListImgAdapter
import com.hankol.material.adapter.ContentListVideoAdapter
import com.hankol.material.bean.FolderListBean
import com.hankol.material.bean.MaterialBusinessBean
import com.hankol.material.bean.TabConfigure
import com.hankol.material.databinding.FragmentListBinding
import com.hankol.material.help.MaterialHelp
import com.hankol.material.viewmodel.MaterialContentViewModel
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*


/**
 * @author: 关忆北丶
 * @time: 2021/10/18 14:46
 * @description: 图片/视频/文档 列表界面
 */
class ContentListFragment(private var bean: MaterialBusinessBean, var listener: MaterialControlContentFragment.OnNumberListener?, private var appBar: AppBarLayout?, var isFromCollect: Boolean = false, var activity: Activity) : BaseFragment() {
    private lateinit var dataBinding: FragmentListBinding
    private lateinit var mViewModel: MaterialContentViewModel
    private var contentListImgAdapter: ContentListImgAdapter? = null
    private var mContentListVideoAdapter: ContentListVideoAdapter? = null
    private var mContentListFolderAdapter: ContentListFolderAdapter? = null
    private var mediaType = -1
    private var pager: Int = 1
    private var isRefresh = true
    var isGoTop = false
    override fun getLayoutId(): Int {
        return R.layout.fragment_list
    }

    companion object {
        fun newInstance(type: Int, bean: MaterialBusinessBean, listener: MaterialControlContentFragment.OnNumberListener?, appBar: AppBarLayout?, isFromCollect: Boolean = false, activity: Activity): ContentListFragment {
            val fragment = ContentListFragment(bean, listener, appBar, isFromCollect, activity)
            val args = Bundle()
            args.putInt("type", type)
            fragment.arguments = args
            return fragment
        }
    }


    override fun init() {
        dataBinding = getDataBinding<FragmentListBinding>()
        mViewModel = getFragmentViewModelProvider(this).get(MaterialContentViewModel::class.java)
        arguments?.let {
            mediaType = it.getInt("type", -1)
        }

        mViewModel.contentInfoList.observe(this, androidx.lifecycle.Observer {
            dataBinding.srfContentListImg.finishRefresh()//结束刷新
            dataBinding.srfContentListImg.finishLoadMore()//结束加载
            hideLoadingDialog()
            if (it == null) return@Observer

            when (mediaType) {
                TabConfigure.IMG.tabConfig -> {
                    if (isRefresh) {
                        if (it.fileLibs.data.size > 0) {
                            dataBinding.rvContentListImg.visibility = View.VISIBLE
                            dataBinding.tvContentListEmpty.visibility = View.GONE
                            contentListImgAdapter?.setData(it.fileLibs.data, isFromCollect)
                        } else {
                            dataBinding.tvContentListEmpty.visibility = View.VISIBLE
                            dataBinding.rvContentListImg.visibility = View.GONE
                        }
                    } else {
                        contentListImgAdapter?.addData(it.fileLibs.data, isFromCollect)
                    }
                    if (it.fileLibs.data.size > 0) {
                        pager++
                    }
                }

                TabConfigure.VIDEO.tabConfig -> {
                    if (isRefresh) {
                        if (it.fileLibs.data.size > 0) {
                            dataBinding.rvContentListImg.visibility = View.VISIBLE
                            dataBinding.tvContentListEmpty.visibility = View.GONE
                            mContentListVideoAdapter?.deactivate()
                            mContentListVideoAdapter?.setData(it.fileLibs.data)
                        } else {
                            dataBinding.tvContentListEmpty.visibility = View.VISIBLE
                            dataBinding.rvContentListImg.visibility = View.GONE
                        }
                    } else {
                        mContentListVideoAdapter?.addData(it.fileLibs.data)
                    }
                    if (it.fileLibs.data.size > 0) {
                        pager++
                    }
                }

                TabConfigure.FILE.tabConfig -> {
                    if (isRefresh) {
                        if (it.fileLibs.data.size > 0) {
                            dataBinding.rvContentListImg.visibility = View.VISIBLE
                            dataBinding.tvContentListEmpty.visibility = View.GONE
                            mContentListFolderAdapter?.setNewData(it.fileLibs.data)
                        } else {
                            dataBinding.tvContentListEmpty.visibility = View.VISIBLE
                            dataBinding.rvContentListImg.visibility = View.GONE
                        }
                    } else {
                        mContentListFolderAdapter?.addData(it.fileLibs.data)
                    }
                    if (it.fileLibs.data.size > 0) {
                        pager++
                    }
                }

            }

        })

        initListener()
        loadData()
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
    }

    @SuppressLint("UseRequireInsteadOfGet")
    private fun loadData() {
        when (mediaType) {
            TabConfigure.IMG.tabConfig -> {
                dataBinding.rvContentListImg.layoutManager =
                    context?.let { mViewModel.getGridLayout(it, 2) }
                contentListImgAdapter = ContentListImgAdapter()
                contentListImgAdapter!!.collectionFolderId = bean.collectionId

                dataBinding.rvContentListImg.adapter = contentListImgAdapter
                mViewModel.screenVisible(this, dataBinding.rvContentListImg, dataBinding.llContentListTop, appBar)
            }

            TabConfigure.VIDEO.tabConfig -> {
                dataBinding.rvContentListImg.layoutManager =
                    mViewModel.getLinearLayout(Objects.requireNonNull<Context>(context))
                mContentListVideoAdapter =
                    ContentListVideoAdapter(this, mViewModel, this, bean.searchContent, activity)
                mContentListVideoAdapter!!.collectionFolderId = bean.collectionId
                mContentListVideoAdapter!!.setListener()
                dataBinding.rvContentListImg.adapter = mContentListVideoAdapter
                mViewModel.screenVisible(this, dataBinding.rvContentListImg, dataBinding.llContentListTop, appBar)

            }

            TabConfigure.FILE.tabConfig -> {
                dataBinding.rvContentListImg.layoutManager =
                    mViewModel.getLinearLayout(Objects.requireNonNull<Context>(context))
                mContentListFolderAdapter = ContentListFolderAdapter(mViewModel, this, this, bean)
                mContentListFolderAdapter!!.collectionFolderId = bean.collectionId

                dataBinding.rvContentListImg.adapter = mContentListFolderAdapter
                mViewModel.screenVisible(this, dataBinding.rvContentListImg, dataBinding.llContentListTop, appBar)
            }
        }

        mViewModel.handlerData(bean, mediaType, pager)
    }

    fun initListener() {
        dataBinding.srfContentListImg.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                isRefresh = false
                mViewModel.handlerData(bean, mediaType, pager)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                pager = 1
                isRefresh = true
                mViewModel.handlerData(bean, mediaType, pager)
                EventBusUtils.sendNotify(MessageBus.msgid_tab_refresh)
            }

        })

        dataBinding.llContentListTop.setOnClickListener {
            isGoTop = true
            dataBinding.rvContentListImg.smoothScrollToPosition(0)
        }
    }


    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN) fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgId_material_createFolder) {
            mViewModel.createFolderListener?.onCreateFolder(messageBus.param1 as FolderListBean)
        } else if (messageBus.codeType == MessageBus.msgId_collect_or_cancel) {
            mContentListFolderAdapter?.upItemData(messageBus.param1 as Int)
        } else if (messageBus.codeType == MessageBus.msgId_material_detCollection) {
            //从详情触发，图片 文档
            val type = messageBus.param1 as Int
            if (type == TabConfigure.IMG.tabConfig) {
                contentListImgAdapter?.let {
                    it.removeCurrentData()
                    if (it.mList.isNullOrEmpty()) {
                        dataBinding.rvContentListImg.visibility = View.GONE
                        dataBinding.tvContentListEmpty.visibility = View.VISIBLE
                    }
                }

            } else if (type == TabConfigure.FILE.tabConfig) {
                mContentListFolderAdapter?.let {
                    it.removeCurrentData()
                    if (it.data.isNullOrEmpty()) {
                        dataBinding.rvContentListImg.visibility = View.GONE
                        dataBinding.tvContentListEmpty.visibility = View.VISIBLE
                    }
                }
            } else if (type == TabConfigure.VIDEO.tabConfig) {
                mContentListVideoAdapter?.let {
                    it.removeCurrentData()
                    if (it.mList.isNullOrEmpty()) {
                        dataBinding.rvContentListImg.visibility = View.GONE
                        dataBinding.tvContentListEmpty.visibility = View.VISIBLE
                    }
                }
            }
        }
    }

    override fun onPause() {
        super.onPause()
        mContentListVideoAdapter?.deactivate()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden) {
            //不可见
            mContentListVideoAdapter?.deactivate()
        }
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (!isVisibleToUser) {
            //不可见
            mContentListVideoAdapter?.deactivate()
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        mContentListVideoAdapter?.deactivate()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
    }

    override fun onResume() {
        super.onResume()
        requireView().isFocusableInTouchMode = true
        requireView().requestFocus()
        requireView().setOnKeyListener(View.OnKeyListener { view, i, keyEvent ->
            if (keyEvent.action == KeyEvent.ACTION_DOWN && i == KeyEvent.KEYCODE_BACK) {
                if (mContentListVideoAdapter != null && mContentListVideoAdapter?.mHKPlayVideo != null) {
                    mContentListVideoAdapter?.mHKPlayVideo?.let {
                        return@OnKeyListener it.setKeyDown()
                    }
                }
                return@OnKeyListener false
            }
            false
        })
    }
}
